/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.connection.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import studio.raptor.ddal.core.connection.BackendConnection;
import studio.raptor.ddal.core.executor.resultset.ResultData;

/**
 * Backend connection based on jdbc implementation.
 *
 * @author Sam
 * @since 3.0.0
 */
public class JdbcBackendConnection extends BackendConnection {

  private static Logger LOGGER = LoggerFactory.getLogger(JdbcBackendConnection.class);

  /**
   * Jdbc connection
   */
  private Connection connection;
  private boolean isReadOnly = true;
  private int fetchSize;
  private String lastValidateSql;

  JdbcBackendConnection(Connection connection) {
    super();
    this.connection = connection;
  }

  @Override
  public void setAutoCommit(boolean autoCommit) throws SQLException{
    this.connection.setAutoCommit(autoCommit);
  }

  void setFetchSize(int fetchSize) {
    this.fetchSize = fetchSize;
  }

  @Override
  public boolean validate(String checkQuery, int timeout) {
    if (checkQuery == null || checkQuery.length() == 0) {
      try {
        if (timeout < 0) {
          timeout = 0;
        }
        return connection.isValid(timeout);
      } catch (SQLException e) {
        LOGGER.error(String.format("Connection [%s] will be removed from pool because of validation failure", connection), e);
        return false;
      }
    }

    if (!checkQuery.equals(lastValidateSql)) {
      lastValidateSql = checkQuery;
    }

    try (
            PreparedStatement preparedStatement = connection.prepareStatement(lastValidateSql);
            ResultSet resultSet = preparedStatement.executeQuery()
    ) {
      return resultSet.next();
    } catch (SQLException e) {
      LOGGER.error(String.format("Connection [%s] will be removed from pool because of validation failure", connection), e);
      return false;
    }
  }

  @Override
  public boolean isReadOnly() throws SQLException {
    return this.isReadOnly;
  }

  @Override
  public void setIsReadOnly(boolean readOnly) throws SQLException {
    this.isReadOnly = readOnly;
  }

  public void rollback() throws SQLException {
    this.connection.rollback();
  }

  public void close() {
    try {
      returnConnection();
    } catch (Exception e) {
      LOGGER.error("Return connection error", e);
    }
  }

  /**
   * 物理连接被真正关闭之后，要把当前连接从连接池中删除。
   */
  @Override
  public void reallyClose() throws SQLException {
    this.connection.close();
    try {
      invalidateConnection();
    } catch (Exception e) {
      LOGGER.error("invalidate connection error", e);
    }
  }

  public void commit() throws SQLException {
    this.connection.commit();
  }

  public ResultData executeQuery(String sql) throws SQLException {
    try (
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql)
    ) {
      rs.setFetchSize(this.fetchSize);
      return new ResultData(rs);
    }
  }

  public ResultData executeUpdate(String sql) throws SQLException {
    try (
            Statement statement = connection.createStatement()
    ) {
      int affectedRows = statement.executeUpdate(sql);
      return new ResultData(affectedRows);
    }
  }

  public ResultData executePreparedQuery(String sql, List<Object> parameters) throws SQLException {
    try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
      this.setParameters(preparedStatement, parameters);
      try (ResultSet rs = preparedStatement.executeQuery()) {
        rs.setFetchSize(this.fetchSize);
        return new ResultData(rs);
      }
    }
  }

  public ResultData executePreparedUpdate(String sql, List<Object> parameters) throws SQLException {
    try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
      setParameters(preparedStatement, parameters);
      int affectedRows = preparedStatement.executeUpdate();
      return new ResultData(affectedRows);
    }
  }

  public void setSchema(String schema) throws SQLException {
    this.connection.setSchema(schema);
  }

  /**
   * 仅供测试
   * @return
   */
  public Connection getRealConnection(){
    return connection;
  }

  /**
   * 预编译语句参数设置
   *
   * @param preparedStatement 预编译语句
   * @param parameters        参数集合
   * @throws SQLException Set parameters error.
   */
  private void setParameters(final PreparedStatement preparedStatement, final List<Object> parameters) throws SQLException {
    int i = 1;
    for (Object each : parameters) {
      preparedStatement.setObject(i++, each);
    }
  }
}
